/**
 * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 */

package com.hellodoctor.slayer.service.persistence;

import com.hellodoctor.slayer.NoSuchAppointmentException;
import com.hellodoctor.slayer.model.Appointment;
import com.hellodoctor.slayer.model.impl.AppointmentImpl;
import com.hellodoctor.slayer.model.impl.AppointmentModelImpl;

import com.liferay.portal.kernel.cache.CacheRegistryUtil;
import com.liferay.portal.kernel.dao.orm.EntityCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderCacheUtil;
import com.liferay.portal.kernel.dao.orm.FinderPath;
import com.liferay.portal.kernel.dao.orm.Query;
import com.liferay.portal.kernel.dao.orm.QueryPos;
import com.liferay.portal.kernel.dao.orm.QueryUtil;
import com.liferay.portal.kernel.dao.orm.Session;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.log.Log;
import com.liferay.portal.kernel.log.LogFactoryUtil;
import com.liferay.portal.kernel.util.CalendarUtil;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.InstanceFactory;
import com.liferay.portal.kernel.util.OrderByComparator;
import com.liferay.portal.kernel.util.PropsKeys;
import com.liferay.portal.kernel.util.PropsUtil;
import com.liferay.portal.kernel.util.StringBundler;
import com.liferay.portal.kernel.util.StringPool;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.kernel.util.UnmodifiableList;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.CacheModel;
import com.liferay.portal.model.ModelListener;
import com.liferay.portal.service.persistence.impl.BasePersistenceImpl;

import java.io.Serializable;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * The persistence implementation for the appointment service.
 *
 * <p>
 * Caching information and settings can be found in <code>portal.properties</code>
 * </p>
 *
 * @author Shahbaj
 * @see AppointmentPersistence
 * @see AppointmentUtil
 * @generated
 */
public class AppointmentPersistenceImpl extends BasePersistenceImpl<Appointment>
	implements AppointmentPersistence {
	/*
	 * NOTE FOR DEVELOPERS:
	 *
	 * Never modify or reference this class directly. Always use {@link AppointmentUtil} to access the appointment persistence. Modify <code>service.xml</code> and rerun ServiceBuilder to regenerate this class.
	 */
	public static final String FINDER_CLASS_NAME_ENTITY = AppointmentImpl.class.getName();
	public static final String FINDER_CLASS_NAME_LIST_WITH_PAGINATION = FINDER_CLASS_NAME_ENTITY +
		".List1";
	public static final String FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION = FINDER_CLASS_NAME_ENTITY +
		".List2";
	public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_ALL = new FinderPath(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
			AppointmentModelImpl.FINDER_CACHE_ENABLED, AppointmentImpl.class,
			FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findAll", new String[0]);
	public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_ALL = new FinderPath(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
			AppointmentModelImpl.FINDER_CACHE_ENABLED, AppointmentImpl.class,
			FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findAll", new String[0]);
	public static final FinderPath FINDER_PATH_COUNT_ALL = new FinderPath(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
			AppointmentModelImpl.FINDER_CACHE_ENABLED, Long.class,
			FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countAll", new String[0]);
	public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_DOCTORID = new FinderPath(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
			AppointmentModelImpl.FINDER_CACHE_ENABLED, AppointmentImpl.class,
			FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findByDoctorId",
			new String[] {
				Long.class.getName(),
				
			Integer.class.getName(), Integer.class.getName(),
				OrderByComparator.class.getName()
			});
	public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DOCTORID =
		new FinderPath(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
			AppointmentModelImpl.FINDER_CACHE_ENABLED, AppointmentImpl.class,
			FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findByDoctorId",
			new String[] { Long.class.getName() },
			AppointmentModelImpl.DOCTORID_COLUMN_BITMASK |
			AppointmentModelImpl.APPOINTMENTDATE_COLUMN_BITMASK |
			AppointmentModelImpl.APPOINTMENTTIME_COLUMN_BITMASK |
			AppointmentModelImpl.STATUS_COLUMN_BITMASK);
	public static final FinderPath FINDER_PATH_COUNT_BY_DOCTORID = new FinderPath(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
			AppointmentModelImpl.FINDER_CACHE_ENABLED, Long.class,
			FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByDoctorId",
			new String[] { Long.class.getName() });

	/**
	 * Returns all the appointments where doctorId = &#63;.
	 *
	 * @param doctorId the doctor ID
	 * @return the matching appointments
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public List<Appointment> findByDoctorId(long doctorId)
		throws SystemException {
		return findByDoctorId(doctorId, QueryUtil.ALL_POS, QueryUtil.ALL_POS,
			null);
	}

	/**
	 * Returns a range of all the appointments where doctorId = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link com.hellodoctor.slayer.model.impl.AppointmentModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
	 * </p>
	 *
	 * @param doctorId the doctor ID
	 * @param start the lower bound of the range of appointments
	 * @param end the upper bound of the range of appointments (not inclusive)
	 * @return the range of matching appointments
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public List<Appointment> findByDoctorId(long doctorId, int start, int end)
		throws SystemException {
		return findByDoctorId(doctorId, start, end, null);
	}

	/**
	 * Returns an ordered range of all the appointments where doctorId = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link com.hellodoctor.slayer.model.impl.AppointmentModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
	 * </p>
	 *
	 * @param doctorId the doctor ID
	 * @param start the lower bound of the range of appointments
	 * @param end the upper bound of the range of appointments (not inclusive)
	 * @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
	 * @return the ordered range of matching appointments
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public List<Appointment> findByDoctorId(long doctorId, int start, int end,
		OrderByComparator orderByComparator) throws SystemException {
		boolean pagination = true;
		FinderPath finderPath = null;
		Object[] finderArgs = null;

		if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
				(orderByComparator == null)) {
			pagination = false;
			finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DOCTORID;
			finderArgs = new Object[] { doctorId };
		}
		else {
			finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_DOCTORID;
			finderArgs = new Object[] { doctorId, start, end, orderByComparator };
		}

		List<Appointment> list = (List<Appointment>)FinderCacheUtil.getResult(finderPath,
				finderArgs, this);

		if ((list != null) && !list.isEmpty()) {
			for (Appointment appointment : list) {
				if ((doctorId != appointment.getDoctorId())) {
					list = null;

					break;
				}
			}
		}

		if (list == null) {
			StringBundler query = null;

			if (orderByComparator != null) {
				query = new StringBundler(3 +
						(orderByComparator.getOrderByFields().length * 3));
			}
			else {
				query = new StringBundler(3);
			}

			query.append(_SQL_SELECT_APPOINTMENT_WHERE);

			query.append(_FINDER_COLUMN_DOCTORID_DOCTORID_2);

			if (orderByComparator != null) {
				appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
					orderByComparator);
			}
			else
			 if (pagination) {
				query.append(AppointmentModelImpl.ORDER_BY_JPQL);
			}

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(doctorId);

				if (!pagination) {
					list = (List<Appointment>)QueryUtil.list(q, getDialect(),
							start, end, false);

					Collections.sort(list);

					list = new UnmodifiableList<Appointment>(list);
				}
				else {
					list = (List<Appointment>)QueryUtil.list(q, getDialect(),
							start, end);
				}

				cacheResult(list);

				FinderCacheUtil.putResult(finderPath, finderArgs, list);
			}
			catch (Exception e) {
				FinderCacheUtil.removeResult(finderPath, finderArgs);

				throw processException(e);
			}
			finally {
				closeSession(session);
			}
		}

		return list;
	}

	/**
	 * Returns the first appointment in the ordered set where doctorId = &#63;.
	 *
	 * @param doctorId the doctor ID
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the first matching appointment
	 * @throws com.hellodoctor.slayer.NoSuchAppointmentException if a matching appointment could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment findByDoctorId_First(long doctorId,
		OrderByComparator orderByComparator)
		throws NoSuchAppointmentException, SystemException {
		Appointment appointment = fetchByDoctorId_First(doctorId,
				orderByComparator);

		if (appointment != null) {
			return appointment;
		}

		StringBundler msg = new StringBundler(4);

		msg.append(_NO_SUCH_ENTITY_WITH_KEY);

		msg.append("doctorId=");
		msg.append(doctorId);

		msg.append(StringPool.CLOSE_CURLY_BRACE);

		throw new NoSuchAppointmentException(msg.toString());
	}

	/**
	 * Returns the first appointment in the ordered set where doctorId = &#63;.
	 *
	 * @param doctorId the doctor ID
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the first matching appointment, or <code>null</code> if a matching appointment could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment fetchByDoctorId_First(long doctorId,
		OrderByComparator orderByComparator) throws SystemException {
		List<Appointment> list = findByDoctorId(doctorId, 0, 1,
				orderByComparator);

		if (!list.isEmpty()) {
			return list.get(0);
		}

		return null;
	}

	/**
	 * Returns the last appointment in the ordered set where doctorId = &#63;.
	 *
	 * @param doctorId the doctor ID
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the last matching appointment
	 * @throws com.hellodoctor.slayer.NoSuchAppointmentException if a matching appointment could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment findByDoctorId_Last(long doctorId,
		OrderByComparator orderByComparator)
		throws NoSuchAppointmentException, SystemException {
		Appointment appointment = fetchByDoctorId_Last(doctorId,
				orderByComparator);

		if (appointment != null) {
			return appointment;
		}

		StringBundler msg = new StringBundler(4);

		msg.append(_NO_SUCH_ENTITY_WITH_KEY);

		msg.append("doctorId=");
		msg.append(doctorId);

		msg.append(StringPool.CLOSE_CURLY_BRACE);

		throw new NoSuchAppointmentException(msg.toString());
	}

	/**
	 * Returns the last appointment in the ordered set where doctorId = &#63;.
	 *
	 * @param doctorId the doctor ID
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the last matching appointment, or <code>null</code> if a matching appointment could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment fetchByDoctorId_Last(long doctorId,
		OrderByComparator orderByComparator) throws SystemException {
		int count = countByDoctorId(doctorId);

		if (count == 0) {
			return null;
		}

		List<Appointment> list = findByDoctorId(doctorId, count - 1, count,
				orderByComparator);

		if (!list.isEmpty()) {
			return list.get(0);
		}

		return null;
	}

	/**
	 * Returns the appointments before and after the current appointment in the ordered set where doctorId = &#63;.
	 *
	 * @param appointmentId the primary key of the current appointment
	 * @param doctorId the doctor ID
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the previous, current, and next appointment
	 * @throws com.hellodoctor.slayer.NoSuchAppointmentException if a appointment with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment[] findByDoctorId_PrevAndNext(long appointmentId,
		long doctorId, OrderByComparator orderByComparator)
		throws NoSuchAppointmentException, SystemException {
		Appointment appointment = findByPrimaryKey(appointmentId);

		Session session = null;

		try {
			session = openSession();

			Appointment[] array = new AppointmentImpl[3];

			array[0] = getByDoctorId_PrevAndNext(session, appointment,
					doctorId, orderByComparator, true);

			array[1] = appointment;

			array[2] = getByDoctorId_PrevAndNext(session, appointment,
					doctorId, orderByComparator, false);

			return array;
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}
	}

	protected Appointment getByDoctorId_PrevAndNext(Session session,
		Appointment appointment, long doctorId,
		OrderByComparator orderByComparator, boolean previous) {
		StringBundler query = null;

		if (orderByComparator != null) {
			query = new StringBundler(6 +
					(orderByComparator.getOrderByFields().length * 6));
		}
		else {
			query = new StringBundler(3);
		}

		query.append(_SQL_SELECT_APPOINTMENT_WHERE);

		query.append(_FINDER_COLUMN_DOCTORID_DOCTORID_2);

		if (orderByComparator != null) {
			String[] orderByConditionFields = orderByComparator.getOrderByConditionFields();

			if (orderByConditionFields.length > 0) {
				query.append(WHERE_AND);
			}

			for (int i = 0; i < orderByConditionFields.length; i++) {
				query.append(_ORDER_BY_ENTITY_ALIAS);
				query.append(orderByConditionFields[i]);

				if ((i + 1) < orderByConditionFields.length) {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(WHERE_GREATER_THAN_HAS_NEXT);
					}
					else {
						query.append(WHERE_LESSER_THAN_HAS_NEXT);
					}
				}
				else {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(WHERE_GREATER_THAN);
					}
					else {
						query.append(WHERE_LESSER_THAN);
					}
				}
			}

			query.append(ORDER_BY_CLAUSE);

			String[] orderByFields = orderByComparator.getOrderByFields();

			for (int i = 0; i < orderByFields.length; i++) {
				query.append(_ORDER_BY_ENTITY_ALIAS);
				query.append(orderByFields[i]);

				if ((i + 1) < orderByFields.length) {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(ORDER_BY_ASC_HAS_NEXT);
					}
					else {
						query.append(ORDER_BY_DESC_HAS_NEXT);
					}
				}
				else {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(ORDER_BY_ASC);
					}
					else {
						query.append(ORDER_BY_DESC);
					}
				}
			}
		}
		else {
			query.append(AppointmentModelImpl.ORDER_BY_JPQL);
		}

		String sql = query.toString();

		Query q = session.createQuery(sql);

		q.setFirstResult(0);
		q.setMaxResults(2);

		QueryPos qPos = QueryPos.getInstance(q);

		qPos.add(doctorId);

		if (orderByComparator != null) {
			Object[] values = orderByComparator.getOrderByConditionValues(appointment);

			for (Object value : values) {
				qPos.add(value);
			}
		}

		List<Appointment> list = q.list();

		if (list.size() == 2) {
			return list.get(1);
		}
		else {
			return null;
		}
	}

	/**
	 * Removes all the appointments where doctorId = &#63; from the database.
	 *
	 * @param doctorId the doctor ID
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public void removeByDoctorId(long doctorId) throws SystemException {
		for (Appointment appointment : findByDoctorId(doctorId,
				QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
			remove(appointment);
		}
	}

	/**
	 * Returns the number of appointments where doctorId = &#63;.
	 *
	 * @param doctorId the doctor ID
	 * @return the number of matching appointments
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public int countByDoctorId(long doctorId) throws SystemException {
		FinderPath finderPath = FINDER_PATH_COUNT_BY_DOCTORID;

		Object[] finderArgs = new Object[] { doctorId };

		Long count = (Long)FinderCacheUtil.getResult(finderPath, finderArgs,
				this);

		if (count == null) {
			StringBundler query = new StringBundler(2);

			query.append(_SQL_COUNT_APPOINTMENT_WHERE);

			query.append(_FINDER_COLUMN_DOCTORID_DOCTORID_2);

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(doctorId);

				count = (Long)q.uniqueResult();

				FinderCacheUtil.putResult(finderPath, finderArgs, count);
			}
			catch (Exception e) {
				FinderCacheUtil.removeResult(finderPath, finderArgs);

				throw processException(e);
			}
			finally {
				closeSession(session);
			}
		}

		return count.intValue();
	}

	private static final String _FINDER_COLUMN_DOCTORID_DOCTORID_2 = "appointment.doctorId = ?";
	public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_PATIENTID =
		new FinderPath(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
			AppointmentModelImpl.FINDER_CACHE_ENABLED, AppointmentImpl.class,
			FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findByPatientId",
			new String[] {
				Long.class.getName(),
				
			Integer.class.getName(), Integer.class.getName(),
				OrderByComparator.class.getName()
			});
	public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_PATIENTID =
		new FinderPath(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
			AppointmentModelImpl.FINDER_CACHE_ENABLED, AppointmentImpl.class,
			FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findByPatientId",
			new String[] { Long.class.getName() },
			AppointmentModelImpl.PATIENTID_COLUMN_BITMASK |
			AppointmentModelImpl.APPOINTMENTDATE_COLUMN_BITMASK |
			AppointmentModelImpl.APPOINTMENTTIME_COLUMN_BITMASK |
			AppointmentModelImpl.STATUS_COLUMN_BITMASK);
	public static final FinderPath FINDER_PATH_COUNT_BY_PATIENTID = new FinderPath(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
			AppointmentModelImpl.FINDER_CACHE_ENABLED, Long.class,
			FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByPatientId",
			new String[] { Long.class.getName() });

	/**
	 * Returns all the appointments where patientId = &#63;.
	 *
	 * @param patientId the patient ID
	 * @return the matching appointments
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public List<Appointment> findByPatientId(long patientId)
		throws SystemException {
		return findByPatientId(patientId, QueryUtil.ALL_POS, QueryUtil.ALL_POS,
			null);
	}

	/**
	 * Returns a range of all the appointments where patientId = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link com.hellodoctor.slayer.model.impl.AppointmentModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
	 * </p>
	 *
	 * @param patientId the patient ID
	 * @param start the lower bound of the range of appointments
	 * @param end the upper bound of the range of appointments (not inclusive)
	 * @return the range of matching appointments
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public List<Appointment> findByPatientId(long patientId, int start, int end)
		throws SystemException {
		return findByPatientId(patientId, start, end, null);
	}

	/**
	 * Returns an ordered range of all the appointments where patientId = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link com.hellodoctor.slayer.model.impl.AppointmentModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
	 * </p>
	 *
	 * @param patientId the patient ID
	 * @param start the lower bound of the range of appointments
	 * @param end the upper bound of the range of appointments (not inclusive)
	 * @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
	 * @return the ordered range of matching appointments
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public List<Appointment> findByPatientId(long patientId, int start,
		int end, OrderByComparator orderByComparator) throws SystemException {
		boolean pagination = true;
		FinderPath finderPath = null;
		Object[] finderArgs = null;

		if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
				(orderByComparator == null)) {
			pagination = false;
			finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_PATIENTID;
			finderArgs = new Object[] { patientId };
		}
		else {
			finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_PATIENTID;
			finderArgs = new Object[] { patientId, start, end, orderByComparator };
		}

		List<Appointment> list = (List<Appointment>)FinderCacheUtil.getResult(finderPath,
				finderArgs, this);

		if ((list != null) && !list.isEmpty()) {
			for (Appointment appointment : list) {
				if ((patientId != appointment.getPatientId())) {
					list = null;

					break;
				}
			}
		}

		if (list == null) {
			StringBundler query = null;

			if (orderByComparator != null) {
				query = new StringBundler(3 +
						(orderByComparator.getOrderByFields().length * 3));
			}
			else {
				query = new StringBundler(3);
			}

			query.append(_SQL_SELECT_APPOINTMENT_WHERE);

			query.append(_FINDER_COLUMN_PATIENTID_PATIENTID_2);

			if (orderByComparator != null) {
				appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
					orderByComparator);
			}
			else
			 if (pagination) {
				query.append(AppointmentModelImpl.ORDER_BY_JPQL);
			}

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(patientId);

				if (!pagination) {
					list = (List<Appointment>)QueryUtil.list(q, getDialect(),
							start, end, false);

					Collections.sort(list);

					list = new UnmodifiableList<Appointment>(list);
				}
				else {
					list = (List<Appointment>)QueryUtil.list(q, getDialect(),
							start, end);
				}

				cacheResult(list);

				FinderCacheUtil.putResult(finderPath, finderArgs, list);
			}
			catch (Exception e) {
				FinderCacheUtil.removeResult(finderPath, finderArgs);

				throw processException(e);
			}
			finally {
				closeSession(session);
			}
		}

		return list;
	}

	/**
	 * Returns the first appointment in the ordered set where patientId = &#63;.
	 *
	 * @param patientId the patient ID
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the first matching appointment
	 * @throws com.hellodoctor.slayer.NoSuchAppointmentException if a matching appointment could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment findByPatientId_First(long patientId,
		OrderByComparator orderByComparator)
		throws NoSuchAppointmentException, SystemException {
		Appointment appointment = fetchByPatientId_First(patientId,
				orderByComparator);

		if (appointment != null) {
			return appointment;
		}

		StringBundler msg = new StringBundler(4);

		msg.append(_NO_SUCH_ENTITY_WITH_KEY);

		msg.append("patientId=");
		msg.append(patientId);

		msg.append(StringPool.CLOSE_CURLY_BRACE);

		throw new NoSuchAppointmentException(msg.toString());
	}

	/**
	 * Returns the first appointment in the ordered set where patientId = &#63;.
	 *
	 * @param patientId the patient ID
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the first matching appointment, or <code>null</code> if a matching appointment could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment fetchByPatientId_First(long patientId,
		OrderByComparator orderByComparator) throws SystemException {
		List<Appointment> list = findByPatientId(patientId, 0, 1,
				orderByComparator);

		if (!list.isEmpty()) {
			return list.get(0);
		}

		return null;
	}

	/**
	 * Returns the last appointment in the ordered set where patientId = &#63;.
	 *
	 * @param patientId the patient ID
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the last matching appointment
	 * @throws com.hellodoctor.slayer.NoSuchAppointmentException if a matching appointment could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment findByPatientId_Last(long patientId,
		OrderByComparator orderByComparator)
		throws NoSuchAppointmentException, SystemException {
		Appointment appointment = fetchByPatientId_Last(patientId,
				orderByComparator);

		if (appointment != null) {
			return appointment;
		}

		StringBundler msg = new StringBundler(4);

		msg.append(_NO_SUCH_ENTITY_WITH_KEY);

		msg.append("patientId=");
		msg.append(patientId);

		msg.append(StringPool.CLOSE_CURLY_BRACE);

		throw new NoSuchAppointmentException(msg.toString());
	}

	/**
	 * Returns the last appointment in the ordered set where patientId = &#63;.
	 *
	 * @param patientId the patient ID
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the last matching appointment, or <code>null</code> if a matching appointment could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment fetchByPatientId_Last(long patientId,
		OrderByComparator orderByComparator) throws SystemException {
		int count = countByPatientId(patientId);

		if (count == 0) {
			return null;
		}

		List<Appointment> list = findByPatientId(patientId, count - 1, count,
				orderByComparator);

		if (!list.isEmpty()) {
			return list.get(0);
		}

		return null;
	}

	/**
	 * Returns the appointments before and after the current appointment in the ordered set where patientId = &#63;.
	 *
	 * @param appointmentId the primary key of the current appointment
	 * @param patientId the patient ID
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the previous, current, and next appointment
	 * @throws com.hellodoctor.slayer.NoSuchAppointmentException if a appointment with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment[] findByPatientId_PrevAndNext(long appointmentId,
		long patientId, OrderByComparator orderByComparator)
		throws NoSuchAppointmentException, SystemException {
		Appointment appointment = findByPrimaryKey(appointmentId);

		Session session = null;

		try {
			session = openSession();

			Appointment[] array = new AppointmentImpl[3];

			array[0] = getByPatientId_PrevAndNext(session, appointment,
					patientId, orderByComparator, true);

			array[1] = appointment;

			array[2] = getByPatientId_PrevAndNext(session, appointment,
					patientId, orderByComparator, false);

			return array;
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}
	}

	protected Appointment getByPatientId_PrevAndNext(Session session,
		Appointment appointment, long patientId,
		OrderByComparator orderByComparator, boolean previous) {
		StringBundler query = null;

		if (orderByComparator != null) {
			query = new StringBundler(6 +
					(orderByComparator.getOrderByFields().length * 6));
		}
		else {
			query = new StringBundler(3);
		}

		query.append(_SQL_SELECT_APPOINTMENT_WHERE);

		query.append(_FINDER_COLUMN_PATIENTID_PATIENTID_2);

		if (orderByComparator != null) {
			String[] orderByConditionFields = orderByComparator.getOrderByConditionFields();

			if (orderByConditionFields.length > 0) {
				query.append(WHERE_AND);
			}

			for (int i = 0; i < orderByConditionFields.length; i++) {
				query.append(_ORDER_BY_ENTITY_ALIAS);
				query.append(orderByConditionFields[i]);

				if ((i + 1) < orderByConditionFields.length) {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(WHERE_GREATER_THAN_HAS_NEXT);
					}
					else {
						query.append(WHERE_LESSER_THAN_HAS_NEXT);
					}
				}
				else {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(WHERE_GREATER_THAN);
					}
					else {
						query.append(WHERE_LESSER_THAN);
					}
				}
			}

			query.append(ORDER_BY_CLAUSE);

			String[] orderByFields = orderByComparator.getOrderByFields();

			for (int i = 0; i < orderByFields.length; i++) {
				query.append(_ORDER_BY_ENTITY_ALIAS);
				query.append(orderByFields[i]);

				if ((i + 1) < orderByFields.length) {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(ORDER_BY_ASC_HAS_NEXT);
					}
					else {
						query.append(ORDER_BY_DESC_HAS_NEXT);
					}
				}
				else {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(ORDER_BY_ASC);
					}
					else {
						query.append(ORDER_BY_DESC);
					}
				}
			}
		}
		else {
			query.append(AppointmentModelImpl.ORDER_BY_JPQL);
		}

		String sql = query.toString();

		Query q = session.createQuery(sql);

		q.setFirstResult(0);
		q.setMaxResults(2);

		QueryPos qPos = QueryPos.getInstance(q);

		qPos.add(patientId);

		if (orderByComparator != null) {
			Object[] values = orderByComparator.getOrderByConditionValues(appointment);

			for (Object value : values) {
				qPos.add(value);
			}
		}

		List<Appointment> list = q.list();

		if (list.size() == 2) {
			return list.get(1);
		}
		else {
			return null;
		}
	}

	/**
	 * Removes all the appointments where patientId = &#63; from the database.
	 *
	 * @param patientId the patient ID
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public void removeByPatientId(long patientId) throws SystemException {
		for (Appointment appointment : findByPatientId(patientId,
				QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
			remove(appointment);
		}
	}

	/**
	 * Returns the number of appointments where patientId = &#63;.
	 *
	 * @param patientId the patient ID
	 * @return the number of matching appointments
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public int countByPatientId(long patientId) throws SystemException {
		FinderPath finderPath = FINDER_PATH_COUNT_BY_PATIENTID;

		Object[] finderArgs = new Object[] { patientId };

		Long count = (Long)FinderCacheUtil.getResult(finderPath, finderArgs,
				this);

		if (count == null) {
			StringBundler query = new StringBundler(2);

			query.append(_SQL_COUNT_APPOINTMENT_WHERE);

			query.append(_FINDER_COLUMN_PATIENTID_PATIENTID_2);

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(patientId);

				count = (Long)q.uniqueResult();

				FinderCacheUtil.putResult(finderPath, finderArgs, count);
			}
			catch (Exception e) {
				FinderCacheUtil.removeResult(finderPath, finderArgs);

				throw processException(e);
			}
			finally {
				closeSession(session);
			}
		}

		return count.intValue();
	}

	private static final String _FINDER_COLUMN_PATIENTID_PATIENTID_2 = "appointment.patientId = ?";
	public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_PATIENTID_DOCTORID =
		new FinderPath(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
			AppointmentModelImpl.FINDER_CACHE_ENABLED, AppointmentImpl.class,
			FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findByPatientId_DoctorId",
			new String[] {
				Long.class.getName(), Long.class.getName(),
				
			Integer.class.getName(), Integer.class.getName(),
				OrderByComparator.class.getName()
			});
	public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_PATIENTID_DOCTORID =
		new FinderPath(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
			AppointmentModelImpl.FINDER_CACHE_ENABLED, AppointmentImpl.class,
			FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION,
			"findByPatientId_DoctorId",
			new String[] { Long.class.getName(), Long.class.getName() },
			AppointmentModelImpl.PATIENTID_COLUMN_BITMASK |
			AppointmentModelImpl.DOCTORID_COLUMN_BITMASK |
			AppointmentModelImpl.APPOINTMENTDATE_COLUMN_BITMASK |
			AppointmentModelImpl.APPOINTMENTTIME_COLUMN_BITMASK |
			AppointmentModelImpl.STATUS_COLUMN_BITMASK);
	public static final FinderPath FINDER_PATH_COUNT_BY_PATIENTID_DOCTORID = new FinderPath(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
			AppointmentModelImpl.FINDER_CACHE_ENABLED, Long.class,
			FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION,
			"countByPatientId_DoctorId",
			new String[] { Long.class.getName(), Long.class.getName() });

	/**
	 * Returns all the appointments where patientId = &#63; and doctorId = &#63;.
	 *
	 * @param patientId the patient ID
	 * @param doctorId the doctor ID
	 * @return the matching appointments
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public List<Appointment> findByPatientId_DoctorId(long patientId,
		long doctorId) throws SystemException {
		return findByPatientId_DoctorId(patientId, doctorId, QueryUtil.ALL_POS,
			QueryUtil.ALL_POS, null);
	}

	/**
	 * Returns a range of all the appointments where patientId = &#63; and doctorId = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link com.hellodoctor.slayer.model.impl.AppointmentModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
	 * </p>
	 *
	 * @param patientId the patient ID
	 * @param doctorId the doctor ID
	 * @param start the lower bound of the range of appointments
	 * @param end the upper bound of the range of appointments (not inclusive)
	 * @return the range of matching appointments
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public List<Appointment> findByPatientId_DoctorId(long patientId,
		long doctorId, int start, int end) throws SystemException {
		return findByPatientId_DoctorId(patientId, doctorId, start, end, null);
	}

	/**
	 * Returns an ordered range of all the appointments where patientId = &#63; and doctorId = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link com.hellodoctor.slayer.model.impl.AppointmentModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
	 * </p>
	 *
	 * @param patientId the patient ID
	 * @param doctorId the doctor ID
	 * @param start the lower bound of the range of appointments
	 * @param end the upper bound of the range of appointments (not inclusive)
	 * @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
	 * @return the ordered range of matching appointments
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public List<Appointment> findByPatientId_DoctorId(long patientId,
		long doctorId, int start, int end, OrderByComparator orderByComparator)
		throws SystemException {
		boolean pagination = true;
		FinderPath finderPath = null;
		Object[] finderArgs = null;

		if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
				(orderByComparator == null)) {
			pagination = false;
			finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_PATIENTID_DOCTORID;
			finderArgs = new Object[] { patientId, doctorId };
		}
		else {
			finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_PATIENTID_DOCTORID;
			finderArgs = new Object[] {
					patientId, doctorId,
					
					start, end, orderByComparator
				};
		}

		List<Appointment> list = (List<Appointment>)FinderCacheUtil.getResult(finderPath,
				finderArgs, this);

		if ((list != null) && !list.isEmpty()) {
			for (Appointment appointment : list) {
				if ((patientId != appointment.getPatientId()) ||
						(doctorId != appointment.getDoctorId())) {
					list = null;

					break;
				}
			}
		}

		if (list == null) {
			StringBundler query = null;

			if (orderByComparator != null) {
				query = new StringBundler(4 +
						(orderByComparator.getOrderByFields().length * 3));
			}
			else {
				query = new StringBundler(4);
			}

			query.append(_SQL_SELECT_APPOINTMENT_WHERE);

			query.append(_FINDER_COLUMN_PATIENTID_DOCTORID_PATIENTID_2);

			query.append(_FINDER_COLUMN_PATIENTID_DOCTORID_DOCTORID_2);

			if (orderByComparator != null) {
				appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
					orderByComparator);
			}
			else
			 if (pagination) {
				query.append(AppointmentModelImpl.ORDER_BY_JPQL);
			}

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(patientId);

				qPos.add(doctorId);

				if (!pagination) {
					list = (List<Appointment>)QueryUtil.list(q, getDialect(),
							start, end, false);

					Collections.sort(list);

					list = new UnmodifiableList<Appointment>(list);
				}
				else {
					list = (List<Appointment>)QueryUtil.list(q, getDialect(),
							start, end);
				}

				cacheResult(list);

				FinderCacheUtil.putResult(finderPath, finderArgs, list);
			}
			catch (Exception e) {
				FinderCacheUtil.removeResult(finderPath, finderArgs);

				throw processException(e);
			}
			finally {
				closeSession(session);
			}
		}

		return list;
	}

	/**
	 * Returns the first appointment in the ordered set where patientId = &#63; and doctorId = &#63;.
	 *
	 * @param patientId the patient ID
	 * @param doctorId the doctor ID
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the first matching appointment
	 * @throws com.hellodoctor.slayer.NoSuchAppointmentException if a matching appointment could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment findByPatientId_DoctorId_First(long patientId,
		long doctorId, OrderByComparator orderByComparator)
		throws NoSuchAppointmentException, SystemException {
		Appointment appointment = fetchByPatientId_DoctorId_First(patientId,
				doctorId, orderByComparator);

		if (appointment != null) {
			return appointment;
		}

		StringBundler msg = new StringBundler(6);

		msg.append(_NO_SUCH_ENTITY_WITH_KEY);

		msg.append("patientId=");
		msg.append(patientId);

		msg.append(", doctorId=");
		msg.append(doctorId);

		msg.append(StringPool.CLOSE_CURLY_BRACE);

		throw new NoSuchAppointmentException(msg.toString());
	}

	/**
	 * Returns the first appointment in the ordered set where patientId = &#63; and doctorId = &#63;.
	 *
	 * @param patientId the patient ID
	 * @param doctorId the doctor ID
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the first matching appointment, or <code>null</code> if a matching appointment could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment fetchByPatientId_DoctorId_First(long patientId,
		long doctorId, OrderByComparator orderByComparator)
		throws SystemException {
		List<Appointment> list = findByPatientId_DoctorId(patientId, doctorId,
				0, 1, orderByComparator);

		if (!list.isEmpty()) {
			return list.get(0);
		}

		return null;
	}

	/**
	 * Returns the last appointment in the ordered set where patientId = &#63; and doctorId = &#63;.
	 *
	 * @param patientId the patient ID
	 * @param doctorId the doctor ID
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the last matching appointment
	 * @throws com.hellodoctor.slayer.NoSuchAppointmentException if a matching appointment could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment findByPatientId_DoctorId_Last(long patientId,
		long doctorId, OrderByComparator orderByComparator)
		throws NoSuchAppointmentException, SystemException {
		Appointment appointment = fetchByPatientId_DoctorId_Last(patientId,
				doctorId, orderByComparator);

		if (appointment != null) {
			return appointment;
		}

		StringBundler msg = new StringBundler(6);

		msg.append(_NO_SUCH_ENTITY_WITH_KEY);

		msg.append("patientId=");
		msg.append(patientId);

		msg.append(", doctorId=");
		msg.append(doctorId);

		msg.append(StringPool.CLOSE_CURLY_BRACE);

		throw new NoSuchAppointmentException(msg.toString());
	}

	/**
	 * Returns the last appointment in the ordered set where patientId = &#63; and doctorId = &#63;.
	 *
	 * @param patientId the patient ID
	 * @param doctorId the doctor ID
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the last matching appointment, or <code>null</code> if a matching appointment could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment fetchByPatientId_DoctorId_Last(long patientId,
		long doctorId, OrderByComparator orderByComparator)
		throws SystemException {
		int count = countByPatientId_DoctorId(patientId, doctorId);

		if (count == 0) {
			return null;
		}

		List<Appointment> list = findByPatientId_DoctorId(patientId, doctorId,
				count - 1, count, orderByComparator);

		if (!list.isEmpty()) {
			return list.get(0);
		}

		return null;
	}

	/**
	 * Returns the appointments before and after the current appointment in the ordered set where patientId = &#63; and doctorId = &#63;.
	 *
	 * @param appointmentId the primary key of the current appointment
	 * @param patientId the patient ID
	 * @param doctorId the doctor ID
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the previous, current, and next appointment
	 * @throws com.hellodoctor.slayer.NoSuchAppointmentException if a appointment with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment[] findByPatientId_DoctorId_PrevAndNext(
		long appointmentId, long patientId, long doctorId,
		OrderByComparator orderByComparator)
		throws NoSuchAppointmentException, SystemException {
		Appointment appointment = findByPrimaryKey(appointmentId);

		Session session = null;

		try {
			session = openSession();

			Appointment[] array = new AppointmentImpl[3];

			array[0] = getByPatientId_DoctorId_PrevAndNext(session,
					appointment, patientId, doctorId, orderByComparator, true);

			array[1] = appointment;

			array[2] = getByPatientId_DoctorId_PrevAndNext(session,
					appointment, patientId, doctorId, orderByComparator, false);

			return array;
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}
	}

	protected Appointment getByPatientId_DoctorId_PrevAndNext(Session session,
		Appointment appointment, long patientId, long doctorId,
		OrderByComparator orderByComparator, boolean previous) {
		StringBundler query = null;

		if (orderByComparator != null) {
			query = new StringBundler(6 +
					(orderByComparator.getOrderByFields().length * 6));
		}
		else {
			query = new StringBundler(3);
		}

		query.append(_SQL_SELECT_APPOINTMENT_WHERE);

		query.append(_FINDER_COLUMN_PATIENTID_DOCTORID_PATIENTID_2);

		query.append(_FINDER_COLUMN_PATIENTID_DOCTORID_DOCTORID_2);

		if (orderByComparator != null) {
			String[] orderByConditionFields = orderByComparator.getOrderByConditionFields();

			if (orderByConditionFields.length > 0) {
				query.append(WHERE_AND);
			}

			for (int i = 0; i < orderByConditionFields.length; i++) {
				query.append(_ORDER_BY_ENTITY_ALIAS);
				query.append(orderByConditionFields[i]);

				if ((i + 1) < orderByConditionFields.length) {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(WHERE_GREATER_THAN_HAS_NEXT);
					}
					else {
						query.append(WHERE_LESSER_THAN_HAS_NEXT);
					}
				}
				else {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(WHERE_GREATER_THAN);
					}
					else {
						query.append(WHERE_LESSER_THAN);
					}
				}
			}

			query.append(ORDER_BY_CLAUSE);

			String[] orderByFields = orderByComparator.getOrderByFields();

			for (int i = 0; i < orderByFields.length; i++) {
				query.append(_ORDER_BY_ENTITY_ALIAS);
				query.append(orderByFields[i]);

				if ((i + 1) < orderByFields.length) {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(ORDER_BY_ASC_HAS_NEXT);
					}
					else {
						query.append(ORDER_BY_DESC_HAS_NEXT);
					}
				}
				else {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(ORDER_BY_ASC);
					}
					else {
						query.append(ORDER_BY_DESC);
					}
				}
			}
		}
		else {
			query.append(AppointmentModelImpl.ORDER_BY_JPQL);
		}

		String sql = query.toString();

		Query q = session.createQuery(sql);

		q.setFirstResult(0);
		q.setMaxResults(2);

		QueryPos qPos = QueryPos.getInstance(q);

		qPos.add(patientId);

		qPos.add(doctorId);

		if (orderByComparator != null) {
			Object[] values = orderByComparator.getOrderByConditionValues(appointment);

			for (Object value : values) {
				qPos.add(value);
			}
		}

		List<Appointment> list = q.list();

		if (list.size() == 2) {
			return list.get(1);
		}
		else {
			return null;
		}
	}

	/**
	 * Removes all the appointments where patientId = &#63; and doctorId = &#63; from the database.
	 *
	 * @param patientId the patient ID
	 * @param doctorId the doctor ID
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public void removeByPatientId_DoctorId(long patientId, long doctorId)
		throws SystemException {
		for (Appointment appointment : findByPatientId_DoctorId(patientId,
				doctorId, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
			remove(appointment);
		}
	}

	/**
	 * Returns the number of appointments where patientId = &#63; and doctorId = &#63;.
	 *
	 * @param patientId the patient ID
	 * @param doctorId the doctor ID
	 * @return the number of matching appointments
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public int countByPatientId_DoctorId(long patientId, long doctorId)
		throws SystemException {
		FinderPath finderPath = FINDER_PATH_COUNT_BY_PATIENTID_DOCTORID;

		Object[] finderArgs = new Object[] { patientId, doctorId };

		Long count = (Long)FinderCacheUtil.getResult(finderPath, finderArgs,
				this);

		if (count == null) {
			StringBundler query = new StringBundler(3);

			query.append(_SQL_COUNT_APPOINTMENT_WHERE);

			query.append(_FINDER_COLUMN_PATIENTID_DOCTORID_PATIENTID_2);

			query.append(_FINDER_COLUMN_PATIENTID_DOCTORID_DOCTORID_2);

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(patientId);

				qPos.add(doctorId);

				count = (Long)q.uniqueResult();

				FinderCacheUtil.putResult(finderPath, finderArgs, count);
			}
			catch (Exception e) {
				FinderCacheUtil.removeResult(finderPath, finderArgs);

				throw processException(e);
			}
			finally {
				closeSession(session);
			}
		}

		return count.intValue();
	}

	private static final String _FINDER_COLUMN_PATIENTID_DOCTORID_PATIENTID_2 = "appointment.patientId = ? AND ";
	private static final String _FINDER_COLUMN_PATIENTID_DOCTORID_DOCTORID_2 = "appointment.doctorId = ?";
	public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_DOCTORID_ADATE =
		new FinderPath(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
			AppointmentModelImpl.FINDER_CACHE_ENABLED, AppointmentImpl.class,
			FINDER_CLASS_NAME_LIST_WITH_PAGINATION, "findByDoctorId_ADate",
			new String[] {
				Long.class.getName(), Date.class.getName(),
				
			Integer.class.getName(), Integer.class.getName(),
				OrderByComparator.class.getName()
			});
	public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DOCTORID_ADATE =
		new FinderPath(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
			AppointmentModelImpl.FINDER_CACHE_ENABLED, AppointmentImpl.class,
			FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "findByDoctorId_ADate",
			new String[] { Long.class.getName(), Date.class.getName() },
			AppointmentModelImpl.DOCTORID_COLUMN_BITMASK |
			AppointmentModelImpl.APPOINTMENTDATE_COLUMN_BITMASK |
			AppointmentModelImpl.APPOINTMENTTIME_COLUMN_BITMASK |
			AppointmentModelImpl.STATUS_COLUMN_BITMASK);
	public static final FinderPath FINDER_PATH_COUNT_BY_DOCTORID_ADATE = new FinderPath(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
			AppointmentModelImpl.FINDER_CACHE_ENABLED, Long.class,
			FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION, "countByDoctorId_ADate",
			new String[] { Long.class.getName(), Date.class.getName() });

	/**
	 * Returns all the appointments where doctorId = &#63; and appointmentDate = &#63;.
	 *
	 * @param doctorId the doctor ID
	 * @param appointmentDate the appointment date
	 * @return the matching appointments
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public List<Appointment> findByDoctorId_ADate(long doctorId,
		Date appointmentDate) throws SystemException {
		return findByDoctorId_ADate(doctorId, appointmentDate,
			QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
	}

	/**
	 * Returns a range of all the appointments where doctorId = &#63; and appointmentDate = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link com.hellodoctor.slayer.model.impl.AppointmentModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
	 * </p>
	 *
	 * @param doctorId the doctor ID
	 * @param appointmentDate the appointment date
	 * @param start the lower bound of the range of appointments
	 * @param end the upper bound of the range of appointments (not inclusive)
	 * @return the range of matching appointments
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public List<Appointment> findByDoctorId_ADate(long doctorId,
		Date appointmentDate, int start, int end) throws SystemException {
		return findByDoctorId_ADate(doctorId, appointmentDate, start, end, null);
	}

	/**
	 * Returns an ordered range of all the appointments where doctorId = &#63; and appointmentDate = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link com.hellodoctor.slayer.model.impl.AppointmentModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
	 * </p>
	 *
	 * @param doctorId the doctor ID
	 * @param appointmentDate the appointment date
	 * @param start the lower bound of the range of appointments
	 * @param end the upper bound of the range of appointments (not inclusive)
	 * @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
	 * @return the ordered range of matching appointments
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public List<Appointment> findByDoctorId_ADate(long doctorId,
		Date appointmentDate, int start, int end,
		OrderByComparator orderByComparator) throws SystemException {
		boolean pagination = true;
		FinderPath finderPath = null;
		Object[] finderArgs = null;

		if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
				(orderByComparator == null)) {
			pagination = false;
			finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DOCTORID_ADATE;
			finderArgs = new Object[] { doctorId, appointmentDate };
		}
		else {
			finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_DOCTORID_ADATE;
			finderArgs = new Object[] {
					doctorId, appointmentDate,
					
					start, end, orderByComparator
				};
		}

		List<Appointment> list = (List<Appointment>)FinderCacheUtil.getResult(finderPath,
				finderArgs, this);

		if ((list != null) && !list.isEmpty()) {
			for (Appointment appointment : list) {
				if ((doctorId != appointment.getDoctorId()) ||
						!Validator.equals(appointmentDate,
							appointment.getAppointmentDate())) {
					list = null;

					break;
				}
			}
		}

		if (list == null) {
			StringBundler query = null;

			if (orderByComparator != null) {
				query = new StringBundler(4 +
						(orderByComparator.getOrderByFields().length * 3));
			}
			else {
				query = new StringBundler(4);
			}

			query.append(_SQL_SELECT_APPOINTMENT_WHERE);

			query.append(_FINDER_COLUMN_DOCTORID_ADATE_DOCTORID_2);

			boolean bindAppointmentDate = false;

			if (appointmentDate == null) {
				query.append(_FINDER_COLUMN_DOCTORID_ADATE_APPOINTMENTDATE_1);
			}
			else {
				bindAppointmentDate = true;

				query.append(_FINDER_COLUMN_DOCTORID_ADATE_APPOINTMENTDATE_2);
			}

			if (orderByComparator != null) {
				appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
					orderByComparator);
			}
			else
			 if (pagination) {
				query.append(AppointmentModelImpl.ORDER_BY_JPQL);
			}

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(doctorId);

				if (bindAppointmentDate) {
					qPos.add(CalendarUtil.getTimestamp(appointmentDate));
				}

				if (!pagination) {
					list = (List<Appointment>)QueryUtil.list(q, getDialect(),
							start, end, false);

					Collections.sort(list);

					list = new UnmodifiableList<Appointment>(list);
				}
				else {
					list = (List<Appointment>)QueryUtil.list(q, getDialect(),
							start, end);
				}

				cacheResult(list);

				FinderCacheUtil.putResult(finderPath, finderArgs, list);
			}
			catch (Exception e) {
				FinderCacheUtil.removeResult(finderPath, finderArgs);

				throw processException(e);
			}
			finally {
				closeSession(session);
			}
		}

		return list;
	}

	/**
	 * Returns the first appointment in the ordered set where doctorId = &#63; and appointmentDate = &#63;.
	 *
	 * @param doctorId the doctor ID
	 * @param appointmentDate the appointment date
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the first matching appointment
	 * @throws com.hellodoctor.slayer.NoSuchAppointmentException if a matching appointment could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment findByDoctorId_ADate_First(long doctorId,
		Date appointmentDate, OrderByComparator orderByComparator)
		throws NoSuchAppointmentException, SystemException {
		Appointment appointment = fetchByDoctorId_ADate_First(doctorId,
				appointmentDate, orderByComparator);

		if (appointment != null) {
			return appointment;
		}

		StringBundler msg = new StringBundler(6);

		msg.append(_NO_SUCH_ENTITY_WITH_KEY);

		msg.append("doctorId=");
		msg.append(doctorId);

		msg.append(", appointmentDate=");
		msg.append(appointmentDate);

		msg.append(StringPool.CLOSE_CURLY_BRACE);

		throw new NoSuchAppointmentException(msg.toString());
	}

	/**
	 * Returns the first appointment in the ordered set where doctorId = &#63; and appointmentDate = &#63;.
	 *
	 * @param doctorId the doctor ID
	 * @param appointmentDate the appointment date
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the first matching appointment, or <code>null</code> if a matching appointment could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment fetchByDoctorId_ADate_First(long doctorId,
		Date appointmentDate, OrderByComparator orderByComparator)
		throws SystemException {
		List<Appointment> list = findByDoctorId_ADate(doctorId,
				appointmentDate, 0, 1, orderByComparator);

		if (!list.isEmpty()) {
			return list.get(0);
		}

		return null;
	}

	/**
	 * Returns the last appointment in the ordered set where doctorId = &#63; and appointmentDate = &#63;.
	 *
	 * @param doctorId the doctor ID
	 * @param appointmentDate the appointment date
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the last matching appointment
	 * @throws com.hellodoctor.slayer.NoSuchAppointmentException if a matching appointment could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment findByDoctorId_ADate_Last(long doctorId,
		Date appointmentDate, OrderByComparator orderByComparator)
		throws NoSuchAppointmentException, SystemException {
		Appointment appointment = fetchByDoctorId_ADate_Last(doctorId,
				appointmentDate, orderByComparator);

		if (appointment != null) {
			return appointment;
		}

		StringBundler msg = new StringBundler(6);

		msg.append(_NO_SUCH_ENTITY_WITH_KEY);

		msg.append("doctorId=");
		msg.append(doctorId);

		msg.append(", appointmentDate=");
		msg.append(appointmentDate);

		msg.append(StringPool.CLOSE_CURLY_BRACE);

		throw new NoSuchAppointmentException(msg.toString());
	}

	/**
	 * Returns the last appointment in the ordered set where doctorId = &#63; and appointmentDate = &#63;.
	 *
	 * @param doctorId the doctor ID
	 * @param appointmentDate the appointment date
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the last matching appointment, or <code>null</code> if a matching appointment could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment fetchByDoctorId_ADate_Last(long doctorId,
		Date appointmentDate, OrderByComparator orderByComparator)
		throws SystemException {
		int count = countByDoctorId_ADate(doctorId, appointmentDate);

		if (count == 0) {
			return null;
		}

		List<Appointment> list = findByDoctorId_ADate(doctorId,
				appointmentDate, count - 1, count, orderByComparator);

		if (!list.isEmpty()) {
			return list.get(0);
		}

		return null;
	}

	/**
	 * Returns the appointments before and after the current appointment in the ordered set where doctorId = &#63; and appointmentDate = &#63;.
	 *
	 * @param appointmentId the primary key of the current appointment
	 * @param doctorId the doctor ID
	 * @param appointmentDate the appointment date
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the previous, current, and next appointment
	 * @throws com.hellodoctor.slayer.NoSuchAppointmentException if a appointment with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment[] findByDoctorId_ADate_PrevAndNext(long appointmentId,
		long doctorId, Date appointmentDate, OrderByComparator orderByComparator)
		throws NoSuchAppointmentException, SystemException {
		Appointment appointment = findByPrimaryKey(appointmentId);

		Session session = null;

		try {
			session = openSession();

			Appointment[] array = new AppointmentImpl[3];

			array[0] = getByDoctorId_ADate_PrevAndNext(session, appointment,
					doctorId, appointmentDate, orderByComparator, true);

			array[1] = appointment;

			array[2] = getByDoctorId_ADate_PrevAndNext(session, appointment,
					doctorId, appointmentDate, orderByComparator, false);

			return array;
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}
	}

	protected Appointment getByDoctorId_ADate_PrevAndNext(Session session,
		Appointment appointment, long doctorId, Date appointmentDate,
		OrderByComparator orderByComparator, boolean previous) {
		StringBundler query = null;

		if (orderByComparator != null) {
			query = new StringBundler(6 +
					(orderByComparator.getOrderByFields().length * 6));
		}
		else {
			query = new StringBundler(3);
		}

		query.append(_SQL_SELECT_APPOINTMENT_WHERE);

		query.append(_FINDER_COLUMN_DOCTORID_ADATE_DOCTORID_2);

		boolean bindAppointmentDate = false;

		if (appointmentDate == null) {
			query.append(_FINDER_COLUMN_DOCTORID_ADATE_APPOINTMENTDATE_1);
		}
		else {
			bindAppointmentDate = true;

			query.append(_FINDER_COLUMN_DOCTORID_ADATE_APPOINTMENTDATE_2);
		}

		if (orderByComparator != null) {
			String[] orderByConditionFields = orderByComparator.getOrderByConditionFields();

			if (orderByConditionFields.length > 0) {
				query.append(WHERE_AND);
			}

			for (int i = 0; i < orderByConditionFields.length; i++) {
				query.append(_ORDER_BY_ENTITY_ALIAS);
				query.append(orderByConditionFields[i]);

				if ((i + 1) < orderByConditionFields.length) {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(WHERE_GREATER_THAN_HAS_NEXT);
					}
					else {
						query.append(WHERE_LESSER_THAN_HAS_NEXT);
					}
				}
				else {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(WHERE_GREATER_THAN);
					}
					else {
						query.append(WHERE_LESSER_THAN);
					}
				}
			}

			query.append(ORDER_BY_CLAUSE);

			String[] orderByFields = orderByComparator.getOrderByFields();

			for (int i = 0; i < orderByFields.length; i++) {
				query.append(_ORDER_BY_ENTITY_ALIAS);
				query.append(orderByFields[i]);

				if ((i + 1) < orderByFields.length) {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(ORDER_BY_ASC_HAS_NEXT);
					}
					else {
						query.append(ORDER_BY_DESC_HAS_NEXT);
					}
				}
				else {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(ORDER_BY_ASC);
					}
					else {
						query.append(ORDER_BY_DESC);
					}
				}
			}
		}
		else {
			query.append(AppointmentModelImpl.ORDER_BY_JPQL);
		}

		String sql = query.toString();

		Query q = session.createQuery(sql);

		q.setFirstResult(0);
		q.setMaxResults(2);

		QueryPos qPos = QueryPos.getInstance(q);

		qPos.add(doctorId);

		if (bindAppointmentDate) {
			qPos.add(CalendarUtil.getTimestamp(appointmentDate));
		}

		if (orderByComparator != null) {
			Object[] values = orderByComparator.getOrderByConditionValues(appointment);

			for (Object value : values) {
				qPos.add(value);
			}
		}

		List<Appointment> list = q.list();

		if (list.size() == 2) {
			return list.get(1);
		}
		else {
			return null;
		}
	}

	/**
	 * Removes all the appointments where doctorId = &#63; and appointmentDate = &#63; from the database.
	 *
	 * @param doctorId the doctor ID
	 * @param appointmentDate the appointment date
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public void removeByDoctorId_ADate(long doctorId, Date appointmentDate)
		throws SystemException {
		for (Appointment appointment : findByDoctorId_ADate(doctorId,
				appointmentDate, QueryUtil.ALL_POS, QueryUtil.ALL_POS, null)) {
			remove(appointment);
		}
	}

	/**
	 * Returns the number of appointments where doctorId = &#63; and appointmentDate = &#63;.
	 *
	 * @param doctorId the doctor ID
	 * @param appointmentDate the appointment date
	 * @return the number of matching appointments
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public int countByDoctorId_ADate(long doctorId, Date appointmentDate)
		throws SystemException {
		FinderPath finderPath = FINDER_PATH_COUNT_BY_DOCTORID_ADATE;

		Object[] finderArgs = new Object[] { doctorId, appointmentDate };

		Long count = (Long)FinderCacheUtil.getResult(finderPath, finderArgs,
				this);

		if (count == null) {
			StringBundler query = new StringBundler(3);

			query.append(_SQL_COUNT_APPOINTMENT_WHERE);

			query.append(_FINDER_COLUMN_DOCTORID_ADATE_DOCTORID_2);

			boolean bindAppointmentDate = false;

			if (appointmentDate == null) {
				query.append(_FINDER_COLUMN_DOCTORID_ADATE_APPOINTMENTDATE_1);
			}
			else {
				bindAppointmentDate = true;

				query.append(_FINDER_COLUMN_DOCTORID_ADATE_APPOINTMENTDATE_2);
			}

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(doctorId);

				if (bindAppointmentDate) {
					qPos.add(CalendarUtil.getTimestamp(appointmentDate));
				}

				count = (Long)q.uniqueResult();

				FinderCacheUtil.putResult(finderPath, finderArgs, count);
			}
			catch (Exception e) {
				FinderCacheUtil.removeResult(finderPath, finderArgs);

				throw processException(e);
			}
			finally {
				closeSession(session);
			}
		}

		return count.intValue();
	}

	private static final String _FINDER_COLUMN_DOCTORID_ADATE_DOCTORID_2 = "appointment.doctorId = ? AND ";
	private static final String _FINDER_COLUMN_DOCTORID_ADATE_APPOINTMENTDATE_1 = "appointment.appointmentDate IS NULL";
	private static final String _FINDER_COLUMN_DOCTORID_ADATE_APPOINTMENTDATE_2 = "appointment.appointmentDate = ?";
	public static final FinderPath FINDER_PATH_WITH_PAGINATION_FIND_BY_DOCTORID_ADATE_STATUS =
		new FinderPath(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
			AppointmentModelImpl.FINDER_CACHE_ENABLED, AppointmentImpl.class,
			FINDER_CLASS_NAME_LIST_WITH_PAGINATION,
			"findByDoctorId_ADate_status",
			new String[] {
				Long.class.getName(), Date.class.getName(),
				Integer.class.getName(),
				
			Integer.class.getName(), Integer.class.getName(),
				OrderByComparator.class.getName()
			});
	public static final FinderPath FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DOCTORID_ADATE_STATUS =
		new FinderPath(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
			AppointmentModelImpl.FINDER_CACHE_ENABLED, AppointmentImpl.class,
			FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION,
			"findByDoctorId_ADate_status",
			new String[] {
				Long.class.getName(), Date.class.getName(),
				Integer.class.getName()
			},
			AppointmentModelImpl.DOCTORID_COLUMN_BITMASK |
			AppointmentModelImpl.APPOINTMENTDATE_COLUMN_BITMASK |
			AppointmentModelImpl.STATUS_COLUMN_BITMASK |
			AppointmentModelImpl.APPOINTMENTTIME_COLUMN_BITMASK);
	public static final FinderPath FINDER_PATH_COUNT_BY_DOCTORID_ADATE_STATUS = new FinderPath(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
			AppointmentModelImpl.FINDER_CACHE_ENABLED, Long.class,
			FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION,
			"countByDoctorId_ADate_status",
			new String[] {
				Long.class.getName(), Date.class.getName(),
				Integer.class.getName()
			});

	/**
	 * Returns all the appointments where doctorId = &#63; and appointmentDate = &#63; and status = &#63;.
	 *
	 * @param doctorId the doctor ID
	 * @param appointmentDate the appointment date
	 * @param status the status
	 * @return the matching appointments
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public List<Appointment> findByDoctorId_ADate_status(long doctorId,
		Date appointmentDate, int status) throws SystemException {
		return findByDoctorId_ADate_status(doctorId, appointmentDate, status,
			QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
	}

	/**
	 * Returns a range of all the appointments where doctorId = &#63; and appointmentDate = &#63; and status = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link com.hellodoctor.slayer.model.impl.AppointmentModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
	 * </p>
	 *
	 * @param doctorId the doctor ID
	 * @param appointmentDate the appointment date
	 * @param status the status
	 * @param start the lower bound of the range of appointments
	 * @param end the upper bound of the range of appointments (not inclusive)
	 * @return the range of matching appointments
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public List<Appointment> findByDoctorId_ADate_status(long doctorId,
		Date appointmentDate, int status, int start, int end)
		throws SystemException {
		return findByDoctorId_ADate_status(doctorId, appointmentDate, status,
			start, end, null);
	}

	/**
	 * Returns an ordered range of all the appointments where doctorId = &#63; and appointmentDate = &#63; and status = &#63;.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link com.hellodoctor.slayer.model.impl.AppointmentModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
	 * </p>
	 *
	 * @param doctorId the doctor ID
	 * @param appointmentDate the appointment date
	 * @param status the status
	 * @param start the lower bound of the range of appointments
	 * @param end the upper bound of the range of appointments (not inclusive)
	 * @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
	 * @return the ordered range of matching appointments
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public List<Appointment> findByDoctorId_ADate_status(long doctorId,
		Date appointmentDate, int status, int start, int end,
		OrderByComparator orderByComparator) throws SystemException {
		boolean pagination = true;
		FinderPath finderPath = null;
		Object[] finderArgs = null;

		if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
				(orderByComparator == null)) {
			pagination = false;
			finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DOCTORID_ADATE_STATUS;
			finderArgs = new Object[] { doctorId, appointmentDate, status };
		}
		else {
			finderPath = FINDER_PATH_WITH_PAGINATION_FIND_BY_DOCTORID_ADATE_STATUS;
			finderArgs = new Object[] {
					doctorId, appointmentDate, status,
					
					start, end, orderByComparator
				};
		}

		List<Appointment> list = (List<Appointment>)FinderCacheUtil.getResult(finderPath,
				finderArgs, this);

		if ((list != null) && !list.isEmpty()) {
			for (Appointment appointment : list) {
				if ((doctorId != appointment.getDoctorId()) ||
						!Validator.equals(appointmentDate,
							appointment.getAppointmentDate()) ||
						(status != appointment.getStatus())) {
					list = null;

					break;
				}
			}
		}

		if (list == null) {
			StringBundler query = null;

			if (orderByComparator != null) {
				query = new StringBundler(5 +
						(orderByComparator.getOrderByFields().length * 3));
			}
			else {
				query = new StringBundler(5);
			}

			query.append(_SQL_SELECT_APPOINTMENT_WHERE);

			query.append(_FINDER_COLUMN_DOCTORID_ADATE_STATUS_DOCTORID_2);

			boolean bindAppointmentDate = false;

			if (appointmentDate == null) {
				query.append(_FINDER_COLUMN_DOCTORID_ADATE_STATUS_APPOINTMENTDATE_1);
			}
			else {
				bindAppointmentDate = true;

				query.append(_FINDER_COLUMN_DOCTORID_ADATE_STATUS_APPOINTMENTDATE_2);
			}

			query.append(_FINDER_COLUMN_DOCTORID_ADATE_STATUS_STATUS_2);

			if (orderByComparator != null) {
				appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
					orderByComparator);
			}
			else
			 if (pagination) {
				query.append(AppointmentModelImpl.ORDER_BY_JPQL);
			}

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(doctorId);

				if (bindAppointmentDate) {
					qPos.add(CalendarUtil.getTimestamp(appointmentDate));
				}

				qPos.add(status);

				if (!pagination) {
					list = (List<Appointment>)QueryUtil.list(q, getDialect(),
							start, end, false);

					Collections.sort(list);

					list = new UnmodifiableList<Appointment>(list);
				}
				else {
					list = (List<Appointment>)QueryUtil.list(q, getDialect(),
							start, end);
				}

				cacheResult(list);

				FinderCacheUtil.putResult(finderPath, finderArgs, list);
			}
			catch (Exception e) {
				FinderCacheUtil.removeResult(finderPath, finderArgs);

				throw processException(e);
			}
			finally {
				closeSession(session);
			}
		}

		return list;
	}

	/**
	 * Returns the first appointment in the ordered set where doctorId = &#63; and appointmentDate = &#63; and status = &#63;.
	 *
	 * @param doctorId the doctor ID
	 * @param appointmentDate the appointment date
	 * @param status the status
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the first matching appointment
	 * @throws com.hellodoctor.slayer.NoSuchAppointmentException if a matching appointment could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment findByDoctorId_ADate_status_First(long doctorId,
		Date appointmentDate, int status, OrderByComparator orderByComparator)
		throws NoSuchAppointmentException, SystemException {
		Appointment appointment = fetchByDoctorId_ADate_status_First(doctorId,
				appointmentDate, status, orderByComparator);

		if (appointment != null) {
			return appointment;
		}

		StringBundler msg = new StringBundler(8);

		msg.append(_NO_SUCH_ENTITY_WITH_KEY);

		msg.append("doctorId=");
		msg.append(doctorId);

		msg.append(", appointmentDate=");
		msg.append(appointmentDate);

		msg.append(", status=");
		msg.append(status);

		msg.append(StringPool.CLOSE_CURLY_BRACE);

		throw new NoSuchAppointmentException(msg.toString());
	}

	/**
	 * Returns the first appointment in the ordered set where doctorId = &#63; and appointmentDate = &#63; and status = &#63;.
	 *
	 * @param doctorId the doctor ID
	 * @param appointmentDate the appointment date
	 * @param status the status
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the first matching appointment, or <code>null</code> if a matching appointment could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment fetchByDoctorId_ADate_status_First(long doctorId,
		Date appointmentDate, int status, OrderByComparator orderByComparator)
		throws SystemException {
		List<Appointment> list = findByDoctorId_ADate_status(doctorId,
				appointmentDate, status, 0, 1, orderByComparator);

		if (!list.isEmpty()) {
			return list.get(0);
		}

		return null;
	}

	/**
	 * Returns the last appointment in the ordered set where doctorId = &#63; and appointmentDate = &#63; and status = &#63;.
	 *
	 * @param doctorId the doctor ID
	 * @param appointmentDate the appointment date
	 * @param status the status
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the last matching appointment
	 * @throws com.hellodoctor.slayer.NoSuchAppointmentException if a matching appointment could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment findByDoctorId_ADate_status_Last(long doctorId,
		Date appointmentDate, int status, OrderByComparator orderByComparator)
		throws NoSuchAppointmentException, SystemException {
		Appointment appointment = fetchByDoctorId_ADate_status_Last(doctorId,
				appointmentDate, status, orderByComparator);

		if (appointment != null) {
			return appointment;
		}

		StringBundler msg = new StringBundler(8);

		msg.append(_NO_SUCH_ENTITY_WITH_KEY);

		msg.append("doctorId=");
		msg.append(doctorId);

		msg.append(", appointmentDate=");
		msg.append(appointmentDate);

		msg.append(", status=");
		msg.append(status);

		msg.append(StringPool.CLOSE_CURLY_BRACE);

		throw new NoSuchAppointmentException(msg.toString());
	}

	/**
	 * Returns the last appointment in the ordered set where doctorId = &#63; and appointmentDate = &#63; and status = &#63;.
	 *
	 * @param doctorId the doctor ID
	 * @param appointmentDate the appointment date
	 * @param status the status
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the last matching appointment, or <code>null</code> if a matching appointment could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment fetchByDoctorId_ADate_status_Last(long doctorId,
		Date appointmentDate, int status, OrderByComparator orderByComparator)
		throws SystemException {
		int count = countByDoctorId_ADate_status(doctorId, appointmentDate,
				status);

		if (count == 0) {
			return null;
		}

		List<Appointment> list = findByDoctorId_ADate_status(doctorId,
				appointmentDate, status, count - 1, count, orderByComparator);

		if (!list.isEmpty()) {
			return list.get(0);
		}

		return null;
	}

	/**
	 * Returns the appointments before and after the current appointment in the ordered set where doctorId = &#63; and appointmentDate = &#63; and status = &#63;.
	 *
	 * @param appointmentId the primary key of the current appointment
	 * @param doctorId the doctor ID
	 * @param appointmentDate the appointment date
	 * @param status the status
	 * @param orderByComparator the comparator to order the set by (optionally <code>null</code>)
	 * @return the previous, current, and next appointment
	 * @throws com.hellodoctor.slayer.NoSuchAppointmentException if a appointment with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment[] findByDoctorId_ADate_status_PrevAndNext(
		long appointmentId, long doctorId, Date appointmentDate, int status,
		OrderByComparator orderByComparator)
		throws NoSuchAppointmentException, SystemException {
		Appointment appointment = findByPrimaryKey(appointmentId);

		Session session = null;

		try {
			session = openSession();

			Appointment[] array = new AppointmentImpl[3];

			array[0] = getByDoctorId_ADate_status_PrevAndNext(session,
					appointment, doctorId, appointmentDate, status,
					orderByComparator, true);

			array[1] = appointment;

			array[2] = getByDoctorId_ADate_status_PrevAndNext(session,
					appointment, doctorId, appointmentDate, status,
					orderByComparator, false);

			return array;
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}
	}

	protected Appointment getByDoctorId_ADate_status_PrevAndNext(
		Session session, Appointment appointment, long doctorId,
		Date appointmentDate, int status, OrderByComparator orderByComparator,
		boolean previous) {
		StringBundler query = null;

		if (orderByComparator != null) {
			query = new StringBundler(6 +
					(orderByComparator.getOrderByFields().length * 6));
		}
		else {
			query = new StringBundler(3);
		}

		query.append(_SQL_SELECT_APPOINTMENT_WHERE);

		query.append(_FINDER_COLUMN_DOCTORID_ADATE_STATUS_DOCTORID_2);

		boolean bindAppointmentDate = false;

		if (appointmentDate == null) {
			query.append(_FINDER_COLUMN_DOCTORID_ADATE_STATUS_APPOINTMENTDATE_1);
		}
		else {
			bindAppointmentDate = true;

			query.append(_FINDER_COLUMN_DOCTORID_ADATE_STATUS_APPOINTMENTDATE_2);
		}

		query.append(_FINDER_COLUMN_DOCTORID_ADATE_STATUS_STATUS_2);

		if (orderByComparator != null) {
			String[] orderByConditionFields = orderByComparator.getOrderByConditionFields();

			if (orderByConditionFields.length > 0) {
				query.append(WHERE_AND);
			}

			for (int i = 0; i < orderByConditionFields.length; i++) {
				query.append(_ORDER_BY_ENTITY_ALIAS);
				query.append(orderByConditionFields[i]);

				if ((i + 1) < orderByConditionFields.length) {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(WHERE_GREATER_THAN_HAS_NEXT);
					}
					else {
						query.append(WHERE_LESSER_THAN_HAS_NEXT);
					}
				}
				else {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(WHERE_GREATER_THAN);
					}
					else {
						query.append(WHERE_LESSER_THAN);
					}
				}
			}

			query.append(ORDER_BY_CLAUSE);

			String[] orderByFields = orderByComparator.getOrderByFields();

			for (int i = 0; i < orderByFields.length; i++) {
				query.append(_ORDER_BY_ENTITY_ALIAS);
				query.append(orderByFields[i]);

				if ((i + 1) < orderByFields.length) {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(ORDER_BY_ASC_HAS_NEXT);
					}
					else {
						query.append(ORDER_BY_DESC_HAS_NEXT);
					}
				}
				else {
					if (orderByComparator.isAscending() ^ previous) {
						query.append(ORDER_BY_ASC);
					}
					else {
						query.append(ORDER_BY_DESC);
					}
				}
			}
		}
		else {
			query.append(AppointmentModelImpl.ORDER_BY_JPQL);
		}

		String sql = query.toString();

		Query q = session.createQuery(sql);

		q.setFirstResult(0);
		q.setMaxResults(2);

		QueryPos qPos = QueryPos.getInstance(q);

		qPos.add(doctorId);

		if (bindAppointmentDate) {
			qPos.add(CalendarUtil.getTimestamp(appointmentDate));
		}

		qPos.add(status);

		if (orderByComparator != null) {
			Object[] values = orderByComparator.getOrderByConditionValues(appointment);

			for (Object value : values) {
				qPos.add(value);
			}
		}

		List<Appointment> list = q.list();

		if (list.size() == 2) {
			return list.get(1);
		}
		else {
			return null;
		}
	}

	/**
	 * Removes all the appointments where doctorId = &#63; and appointmentDate = &#63; and status = &#63; from the database.
	 *
	 * @param doctorId the doctor ID
	 * @param appointmentDate the appointment date
	 * @param status the status
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public void removeByDoctorId_ADate_status(long doctorId,
		Date appointmentDate, int status) throws SystemException {
		for (Appointment appointment : findByDoctorId_ADate_status(doctorId,
				appointmentDate, status, QueryUtil.ALL_POS, QueryUtil.ALL_POS,
				null)) {
			remove(appointment);
		}
	}

	/**
	 * Returns the number of appointments where doctorId = &#63; and appointmentDate = &#63; and status = &#63;.
	 *
	 * @param doctorId the doctor ID
	 * @param appointmentDate the appointment date
	 * @param status the status
	 * @return the number of matching appointments
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public int countByDoctorId_ADate_status(long doctorId,
		Date appointmentDate, int status) throws SystemException {
		FinderPath finderPath = FINDER_PATH_COUNT_BY_DOCTORID_ADATE_STATUS;

		Object[] finderArgs = new Object[] { doctorId, appointmentDate, status };

		Long count = (Long)FinderCacheUtil.getResult(finderPath, finderArgs,
				this);

		if (count == null) {
			StringBundler query = new StringBundler(4);

			query.append(_SQL_COUNT_APPOINTMENT_WHERE);

			query.append(_FINDER_COLUMN_DOCTORID_ADATE_STATUS_DOCTORID_2);

			boolean bindAppointmentDate = false;

			if (appointmentDate == null) {
				query.append(_FINDER_COLUMN_DOCTORID_ADATE_STATUS_APPOINTMENTDATE_1);
			}
			else {
				bindAppointmentDate = true;

				query.append(_FINDER_COLUMN_DOCTORID_ADATE_STATUS_APPOINTMENTDATE_2);
			}

			query.append(_FINDER_COLUMN_DOCTORID_ADATE_STATUS_STATUS_2);

			String sql = query.toString();

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				QueryPos qPos = QueryPos.getInstance(q);

				qPos.add(doctorId);

				if (bindAppointmentDate) {
					qPos.add(CalendarUtil.getTimestamp(appointmentDate));
				}

				qPos.add(status);

				count = (Long)q.uniqueResult();

				FinderCacheUtil.putResult(finderPath, finderArgs, count);
			}
			catch (Exception e) {
				FinderCacheUtil.removeResult(finderPath, finderArgs);

				throw processException(e);
			}
			finally {
				closeSession(session);
			}
		}

		return count.intValue();
	}

	private static final String _FINDER_COLUMN_DOCTORID_ADATE_STATUS_DOCTORID_2 = "appointment.doctorId = ? AND ";
	private static final String _FINDER_COLUMN_DOCTORID_ADATE_STATUS_APPOINTMENTDATE_1 =
		"appointment.appointmentDate IS NULL AND ";
	private static final String _FINDER_COLUMN_DOCTORID_ADATE_STATUS_APPOINTMENTDATE_2 =
		"appointment.appointmentDate = ? AND ";
	private static final String _FINDER_COLUMN_DOCTORID_ADATE_STATUS_STATUS_2 = "appointment.status = ?";

	public AppointmentPersistenceImpl() {
		setModelClass(Appointment.class);
	}

	/**
	 * Caches the appointment in the entity cache if it is enabled.
	 *
	 * @param appointment the appointment
	 */
	@Override
	public void cacheResult(Appointment appointment) {
		EntityCacheUtil.putResult(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
			AppointmentImpl.class, appointment.getPrimaryKey(), appointment);

		appointment.resetOriginalValues();
	}

	/**
	 * Caches the appointments in the entity cache if it is enabled.
	 *
	 * @param appointments the appointments
	 */
	@Override
	public void cacheResult(List<Appointment> appointments) {
		for (Appointment appointment : appointments) {
			if (EntityCacheUtil.getResult(
						AppointmentModelImpl.ENTITY_CACHE_ENABLED,
						AppointmentImpl.class, appointment.getPrimaryKey()) == null) {
				cacheResult(appointment);
			}
			else {
				appointment.resetOriginalValues();
			}
		}
	}

	/**
	 * Clears the cache for all appointments.
	 *
	 * <p>
	 * The {@link com.liferay.portal.kernel.dao.orm.EntityCache} and {@link com.liferay.portal.kernel.dao.orm.FinderCache} are both cleared by this method.
	 * </p>
	 */
	@Override
	public void clearCache() {
		if (_HIBERNATE_CACHE_USE_SECOND_LEVEL_CACHE) {
			CacheRegistryUtil.clear(AppointmentImpl.class.getName());
		}

		EntityCacheUtil.clearCache(AppointmentImpl.class.getName());

		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_ENTITY);
		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
	}

	/**
	 * Clears the cache for the appointment.
	 *
	 * <p>
	 * The {@link com.liferay.portal.kernel.dao.orm.EntityCache} and {@link com.liferay.portal.kernel.dao.orm.FinderCache} are both cleared by this method.
	 * </p>
	 */
	@Override
	public void clearCache(Appointment appointment) {
		EntityCacheUtil.removeResult(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
			AppointmentImpl.class, appointment.getPrimaryKey());

		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
	}

	@Override
	public void clearCache(List<Appointment> appointments) {
		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);

		for (Appointment appointment : appointments) {
			EntityCacheUtil.removeResult(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
				AppointmentImpl.class, appointment.getPrimaryKey());
		}
	}

	/**
	 * Creates a new appointment with the primary key. Does not add the appointment to the database.
	 *
	 * @param appointmentId the primary key for the new appointment
	 * @return the new appointment
	 */
	@Override
	public Appointment create(long appointmentId) {
		Appointment appointment = new AppointmentImpl();

		appointment.setNew(true);
		appointment.setPrimaryKey(appointmentId);

		return appointment;
	}

	/**
	 * Removes the appointment with the primary key from the database. Also notifies the appropriate model listeners.
	 *
	 * @param appointmentId the primary key of the appointment
	 * @return the appointment that was removed
	 * @throws com.hellodoctor.slayer.NoSuchAppointmentException if a appointment with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment remove(long appointmentId)
		throws NoSuchAppointmentException, SystemException {
		return remove((Serializable)appointmentId);
	}

	/**
	 * Removes the appointment with the primary key from the database. Also notifies the appropriate model listeners.
	 *
	 * @param primaryKey the primary key of the appointment
	 * @return the appointment that was removed
	 * @throws com.hellodoctor.slayer.NoSuchAppointmentException if a appointment with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment remove(Serializable primaryKey)
		throws NoSuchAppointmentException, SystemException {
		Session session = null;

		try {
			session = openSession();

			Appointment appointment = (Appointment)session.get(AppointmentImpl.class,
					primaryKey);

			if (appointment == null) {
				if (_log.isWarnEnabled()) {
					_log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey);
				}

				throw new NoSuchAppointmentException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
					primaryKey);
			}

			return remove(appointment);
		}
		catch (NoSuchAppointmentException nsee) {
			throw nsee;
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}
	}

	@Override
	protected Appointment removeImpl(Appointment appointment)
		throws SystemException {
		appointment = toUnwrappedModel(appointment);

		Session session = null;

		try {
			session = openSession();

			if (!session.contains(appointment)) {
				appointment = (Appointment)session.get(AppointmentImpl.class,
						appointment.getPrimaryKeyObj());
			}

			if (appointment != null) {
				session.delete(appointment);
			}
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}

		if (appointment != null) {
			clearCache(appointment);
		}

		return appointment;
	}

	@Override
	public Appointment updateImpl(
		com.hellodoctor.slayer.model.Appointment appointment)
		throws SystemException {
		appointment = toUnwrappedModel(appointment);

		boolean isNew = appointment.isNew();

		AppointmentModelImpl appointmentModelImpl = (AppointmentModelImpl)appointment;

		Session session = null;

		try {
			session = openSession();

			if (appointment.isNew()) {
				session.save(appointment);

				appointment.setNew(false);
			}
			else {
				session.merge(appointment);
			}
		}
		catch (Exception e) {
			throw processException(e);
		}
		finally {
			closeSession(session);
		}

		FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);

		if (isNew || !AppointmentModelImpl.COLUMN_BITMASK_ENABLED) {
			FinderCacheUtil.clearCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
		}

		else {
			if ((appointmentModelImpl.getColumnBitmask() &
					FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DOCTORID.getColumnBitmask()) != 0) {
				Object[] args = new Object[] {
						appointmentModelImpl.getOriginalDoctorId()
					};

				FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_DOCTORID, args);
				FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DOCTORID,
					args);

				args = new Object[] { appointmentModelImpl.getDoctorId() };

				FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_DOCTORID, args);
				FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DOCTORID,
					args);
			}

			if ((appointmentModelImpl.getColumnBitmask() &
					FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_PATIENTID.getColumnBitmask()) != 0) {
				Object[] args = new Object[] {
						appointmentModelImpl.getOriginalPatientId()
					};

				FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_PATIENTID,
					args);
				FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_PATIENTID,
					args);

				args = new Object[] { appointmentModelImpl.getPatientId() };

				FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_PATIENTID,
					args);
				FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_PATIENTID,
					args);
			}

			if ((appointmentModelImpl.getColumnBitmask() &
					FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_PATIENTID_DOCTORID.getColumnBitmask()) != 0) {
				Object[] args = new Object[] {
						appointmentModelImpl.getOriginalPatientId(),
						appointmentModelImpl.getOriginalDoctorId()
					};

				FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_PATIENTID_DOCTORID,
					args);
				FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_PATIENTID_DOCTORID,
					args);

				args = new Object[] {
						appointmentModelImpl.getPatientId(),
						appointmentModelImpl.getDoctorId()
					};

				FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_PATIENTID_DOCTORID,
					args);
				FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_PATIENTID_DOCTORID,
					args);
			}

			if ((appointmentModelImpl.getColumnBitmask() &
					FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DOCTORID_ADATE.getColumnBitmask()) != 0) {
				Object[] args = new Object[] {
						appointmentModelImpl.getOriginalDoctorId(),
						appointmentModelImpl.getOriginalAppointmentDate()
					};

				FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_DOCTORID_ADATE,
					args);
				FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DOCTORID_ADATE,
					args);

				args = new Object[] {
						appointmentModelImpl.getDoctorId(),
						appointmentModelImpl.getAppointmentDate()
					};

				FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_DOCTORID_ADATE,
					args);
				FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DOCTORID_ADATE,
					args);
			}

			if ((appointmentModelImpl.getColumnBitmask() &
					FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DOCTORID_ADATE_STATUS.getColumnBitmask()) != 0) {
				Object[] args = new Object[] {
						appointmentModelImpl.getOriginalDoctorId(),
						appointmentModelImpl.getOriginalAppointmentDate(),
						appointmentModelImpl.getOriginalStatus()
					};

				FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_DOCTORID_ADATE_STATUS,
					args);
				FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DOCTORID_ADATE_STATUS,
					args);

				args = new Object[] {
						appointmentModelImpl.getDoctorId(),
						appointmentModelImpl.getAppointmentDate(),
						appointmentModelImpl.getStatus()
					};

				FinderCacheUtil.removeResult(FINDER_PATH_COUNT_BY_DOCTORID_ADATE_STATUS,
					args);
				FinderCacheUtil.removeResult(FINDER_PATH_WITHOUT_PAGINATION_FIND_BY_DOCTORID_ADATE_STATUS,
					args);
			}
		}

		EntityCacheUtil.putResult(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
			AppointmentImpl.class, appointment.getPrimaryKey(), appointment);

		return appointment;
	}

	protected Appointment toUnwrappedModel(Appointment appointment) {
		if (appointment instanceof AppointmentImpl) {
			return appointment;
		}

		AppointmentImpl appointmentImpl = new AppointmentImpl();

		appointmentImpl.setNew(appointment.isNew());
		appointmentImpl.setPrimaryKey(appointment.getPrimaryKey());

		appointmentImpl.setAppointmentId(appointment.getAppointmentId());
		appointmentImpl.setDoctorId(appointment.getDoctorId());
		appointmentImpl.setPatientId(appointment.getPatientId());
		appointmentImpl.setAppointmentDate(appointment.getAppointmentDate());
		appointmentImpl.setAppointmentTime(appointment.getAppointmentTime());
		appointmentImpl.setStatus(appointment.getStatus());
		appointmentImpl.setCreateDate(appointment.getCreateDate());
		appointmentImpl.setModifiedDate(appointment.getModifiedDate());

		return appointmentImpl;
	}

	/**
	 * Returns the appointment with the primary key or throws a {@link com.liferay.portal.NoSuchModelException} if it could not be found.
	 *
	 * @param primaryKey the primary key of the appointment
	 * @return the appointment
	 * @throws com.hellodoctor.slayer.NoSuchAppointmentException if a appointment with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment findByPrimaryKey(Serializable primaryKey)
		throws NoSuchAppointmentException, SystemException {
		Appointment appointment = fetchByPrimaryKey(primaryKey);

		if (appointment == null) {
			if (_log.isWarnEnabled()) {
				_log.warn(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY + primaryKey);
			}

			throw new NoSuchAppointmentException(_NO_SUCH_ENTITY_WITH_PRIMARY_KEY +
				primaryKey);
		}

		return appointment;
	}

	/**
	 * Returns the appointment with the primary key or throws a {@link com.hellodoctor.slayer.NoSuchAppointmentException} if it could not be found.
	 *
	 * @param appointmentId the primary key of the appointment
	 * @return the appointment
	 * @throws com.hellodoctor.slayer.NoSuchAppointmentException if a appointment with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment findByPrimaryKey(long appointmentId)
		throws NoSuchAppointmentException, SystemException {
		return findByPrimaryKey((Serializable)appointmentId);
	}

	/**
	 * Returns the appointment with the primary key or returns <code>null</code> if it could not be found.
	 *
	 * @param primaryKey the primary key of the appointment
	 * @return the appointment, or <code>null</code> if a appointment with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment fetchByPrimaryKey(Serializable primaryKey)
		throws SystemException {
		Appointment appointment = (Appointment)EntityCacheUtil.getResult(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
				AppointmentImpl.class, primaryKey);

		if (appointment == _nullAppointment) {
			return null;
		}

		if (appointment == null) {
			Session session = null;

			try {
				session = openSession();

				appointment = (Appointment)session.get(AppointmentImpl.class,
						primaryKey);

				if (appointment != null) {
					cacheResult(appointment);
				}
				else {
					EntityCacheUtil.putResult(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
						AppointmentImpl.class, primaryKey, _nullAppointment);
				}
			}
			catch (Exception e) {
				EntityCacheUtil.removeResult(AppointmentModelImpl.ENTITY_CACHE_ENABLED,
					AppointmentImpl.class, primaryKey);

				throw processException(e);
			}
			finally {
				closeSession(session);
			}
		}

		return appointment;
	}

	/**
	 * Returns the appointment with the primary key or returns <code>null</code> if it could not be found.
	 *
	 * @param appointmentId the primary key of the appointment
	 * @return the appointment, or <code>null</code> if a appointment with the primary key could not be found
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public Appointment fetchByPrimaryKey(long appointmentId)
		throws SystemException {
		return fetchByPrimaryKey((Serializable)appointmentId);
	}

	/**
	 * Returns all the appointments.
	 *
	 * @return the appointments
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public List<Appointment> findAll() throws SystemException {
		return findAll(QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
	}

	/**
	 * Returns a range of all the appointments.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link com.hellodoctor.slayer.model.impl.AppointmentModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
	 * </p>
	 *
	 * @param start the lower bound of the range of appointments
	 * @param end the upper bound of the range of appointments (not inclusive)
	 * @return the range of appointments
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public List<Appointment> findAll(int start, int end)
		throws SystemException {
		return findAll(start, end, null);
	}

	/**
	 * Returns an ordered range of all the appointments.
	 *
	 * <p>
	 * Useful when paginating results. Returns a maximum of <code>end - start</code> instances. <code>start</code> and <code>end</code> are not primary keys, they are indexes in the result set. Thus, <code>0</code> refers to the first result in the set. Setting both <code>start</code> and <code>end</code> to {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS} will return the full result set. If <code>orderByComparator</code> is specified, then the query will include the given ORDER BY logic. If <code>orderByComparator</code> is absent and pagination is required (<code>start</code> and <code>end</code> are not {@link com.liferay.portal.kernel.dao.orm.QueryUtil#ALL_POS}), then the query will include the default ORDER BY logic from {@link com.hellodoctor.slayer.model.impl.AppointmentModelImpl}. If both <code>orderByComparator</code> and pagination are absent, for performance reasons, the query will not have an ORDER BY clause and the returned result set will be sorted on by the primary key in an ascending order.
	 * </p>
	 *
	 * @param start the lower bound of the range of appointments
	 * @param end the upper bound of the range of appointments (not inclusive)
	 * @param orderByComparator the comparator to order the results by (optionally <code>null</code>)
	 * @return the ordered range of appointments
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public List<Appointment> findAll(int start, int end,
		OrderByComparator orderByComparator) throws SystemException {
		boolean pagination = true;
		FinderPath finderPath = null;
		Object[] finderArgs = null;

		if ((start == QueryUtil.ALL_POS) && (end == QueryUtil.ALL_POS) &&
				(orderByComparator == null)) {
			pagination = false;
			finderPath = FINDER_PATH_WITHOUT_PAGINATION_FIND_ALL;
			finderArgs = FINDER_ARGS_EMPTY;
		}
		else {
			finderPath = FINDER_PATH_WITH_PAGINATION_FIND_ALL;
			finderArgs = new Object[] { start, end, orderByComparator };
		}

		List<Appointment> list = (List<Appointment>)FinderCacheUtil.getResult(finderPath,
				finderArgs, this);

		if (list == null) {
			StringBundler query = null;
			String sql = null;

			if (orderByComparator != null) {
				query = new StringBundler(2 +
						(orderByComparator.getOrderByFields().length * 3));

				query.append(_SQL_SELECT_APPOINTMENT);

				appendOrderByComparator(query, _ORDER_BY_ENTITY_ALIAS,
					orderByComparator);

				sql = query.toString();
			}
			else {
				sql = _SQL_SELECT_APPOINTMENT;

				if (pagination) {
					sql = sql.concat(AppointmentModelImpl.ORDER_BY_JPQL);
				}
			}

			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(sql);

				if (!pagination) {
					list = (List<Appointment>)QueryUtil.list(q, getDialect(),
							start, end, false);

					Collections.sort(list);

					list = new UnmodifiableList<Appointment>(list);
				}
				else {
					list = (List<Appointment>)QueryUtil.list(q, getDialect(),
							start, end);
				}

				cacheResult(list);

				FinderCacheUtil.putResult(finderPath, finderArgs, list);
			}
			catch (Exception e) {
				FinderCacheUtil.removeResult(finderPath, finderArgs);

				throw processException(e);
			}
			finally {
				closeSession(session);
			}
		}

		return list;
	}

	/**
	 * Removes all the appointments from the database.
	 *
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public void removeAll() throws SystemException {
		for (Appointment appointment : findAll()) {
			remove(appointment);
		}
	}

	/**
	 * Returns the number of appointments.
	 *
	 * @return the number of appointments
	 * @throws SystemException if a system exception occurred
	 */
	@Override
	public int countAll() throws SystemException {
		Long count = (Long)FinderCacheUtil.getResult(FINDER_PATH_COUNT_ALL,
				FINDER_ARGS_EMPTY, this);

		if (count == null) {
			Session session = null;

			try {
				session = openSession();

				Query q = session.createQuery(_SQL_COUNT_APPOINTMENT);

				count = (Long)q.uniqueResult();

				FinderCacheUtil.putResult(FINDER_PATH_COUNT_ALL,
					FINDER_ARGS_EMPTY, count);
			}
			catch (Exception e) {
				FinderCacheUtil.removeResult(FINDER_PATH_COUNT_ALL,
					FINDER_ARGS_EMPTY);

				throw processException(e);
			}
			finally {
				closeSession(session);
			}
		}

		return count.intValue();
	}

	/**
	 * Initializes the appointment persistence.
	 */
	public void afterPropertiesSet() {
		String[] listenerClassNames = StringUtil.split(GetterUtil.getString(
					com.liferay.util.service.ServiceProps.get(
						"value.object.listener.com.hellodoctor.slayer.model.Appointment")));

		if (listenerClassNames.length > 0) {
			try {
				List<ModelListener<Appointment>> listenersList = new ArrayList<ModelListener<Appointment>>();

				for (String listenerClassName : listenerClassNames) {
					listenersList.add((ModelListener<Appointment>)InstanceFactory.newInstance(
							getClassLoader(), listenerClassName));
				}

				listeners = listenersList.toArray(new ModelListener[listenersList.size()]);
			}
			catch (Exception e) {
				_log.error(e);
			}
		}
	}

	public void destroy() {
		EntityCacheUtil.removeCache(AppointmentImpl.class.getName());
		FinderCacheUtil.removeCache(FINDER_CLASS_NAME_ENTITY);
		FinderCacheUtil.removeCache(FINDER_CLASS_NAME_LIST_WITH_PAGINATION);
		FinderCacheUtil.removeCache(FINDER_CLASS_NAME_LIST_WITHOUT_PAGINATION);
	}

	private static final String _SQL_SELECT_APPOINTMENT = "SELECT appointment FROM Appointment appointment";
	private static final String _SQL_SELECT_APPOINTMENT_WHERE = "SELECT appointment FROM Appointment appointment WHERE ";
	private static final String _SQL_COUNT_APPOINTMENT = "SELECT COUNT(appointment) FROM Appointment appointment";
	private static final String _SQL_COUNT_APPOINTMENT_WHERE = "SELECT COUNT(appointment) FROM Appointment appointment WHERE ";
	private static final String _ORDER_BY_ENTITY_ALIAS = "appointment.";
	private static final String _NO_SUCH_ENTITY_WITH_PRIMARY_KEY = "No Appointment exists with the primary key ";
	private static final String _NO_SUCH_ENTITY_WITH_KEY = "No Appointment exists with the key {";
	private static final boolean _HIBERNATE_CACHE_USE_SECOND_LEVEL_CACHE = GetterUtil.getBoolean(PropsUtil.get(
				PropsKeys.HIBERNATE_CACHE_USE_SECOND_LEVEL_CACHE));
	private static Log _log = LogFactoryUtil.getLog(AppointmentPersistenceImpl.class);
	private static Appointment _nullAppointment = new AppointmentImpl() {
			@Override
			public Object clone() {
				return this;
			}

			@Override
			public CacheModel<Appointment> toCacheModel() {
				return _nullAppointmentCacheModel;
			}
		};

	private static CacheModel<Appointment> _nullAppointmentCacheModel = new CacheModel<Appointment>() {
			@Override
			public Appointment toEntityModel() {
				return _nullAppointment;
			}
		};
}